<template>
	<view class="table">
		<!-- 表头 -->
		<view class="row header">
			<text class="cell header-cell">周课表</text>
			<text class="cell header-cell">一</text>
			<text class="cell header-cell">二</text>
			<text class="cell header-cell">三</text>
			<text class="cell header-cell">四</text>
			<text class="cell header-cell">五</text>
			<text class="cell header-cell">六</text>
			<text class="cell header-cell">日</text>
		</view>

		<!-- 表格内容 -->
		<view class="row" v-for="(item, index) in data" :key="index">
			<text class="cell">{{ item.time }}</text>
			<block v-for="(a_item,a_index) in item.children" :key="a_index">
				<text class="cell" @click="checkIndex(index,a_index)">{{ a_item.is_setting == 0 ? '' : '✔'}}</text>
			</block>
		</view>
	</view>
</template>

<script>
	import {getTime} from '../../api/Home.js';
	export default {
		props: {
			value: {
				type: [String, Number],
				default: null
			}
		},
		data() {
			return {
				data: [],
				Is_Index: 1
			};
		},
		watch: {
			'value': function(newval,val) {
				this.Is_Index = newval;
				if(newval < val){
					this.nullData();
				}
			}
		},
		mounted() {
			this.getTime();
		},
		methods: {
			async getTime(){
				try{
					const res = await getTime();
					this.data = [...res.data];
				}catch(err){
					//TODO handle the exception
					console.log(err);
				}
			},
			checkIndex(index1, index2) {
				if (this.calculateStats(this.data) < this.Is_Index || this.data[index1].children[index2].is_setting == 1) {
					this.$set(this.data[index1].children[index2], 'is_setting', this.data[index1].children[index2].is_setting == 0 ? 1 : 0);
					uni.$emit('kcCheck', this.data);
				} else {
					uni.showToast({
						title: '已超出规定选择！',
						icon: 'none',
						duration: 2000
					});
					return false;
				}
			},
			calculateStats(childrens) {
				var num = 0;
				for(var i=0; i<childrens.length; i++){
					for(var j=0; j<childrens[i].children.length; j++){
						if(childrens[i].children[j].is_setting == 1){
							num++;
						}
					}
				}
				return num;
			},
			nullData(){
				for(var i=0; i<this.data.length; i++){
					for(var j=0; j<this.data[i].children.length; j++){
						this.data[i].children[j].is_setting = 0;
					}
				}
			}
		}
	};
</script>

<style scoped>
	.table {
		width: 100%;
	}

	.row {
		display: flex;
		flex-direction: row;
		width: 100%;
	}

	.cell {
		flex: 1;
		padding: 10rpx;
		border: 1px solid #e4eeff;
		text-align: center;
		font-size:26rpx;
	}

	.header {
		font-weight: bold;
	}
</style>